<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex">
          <h1 class="f16">月生产状况</h1>
          <el-button class="primaryBth ml20" type="primary" size="default" @click="removeCurrentRow">移出指令</el-button>
        </div>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          class="mt10"
          :getTableList="getTableList"
          @confirmChange="confirmChange"
          @currentRow="currentRow"
          :isLoading="isLoading"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px' }">
        <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { selectList } from '@/plugins/mixin'
import type { formListType } from '@/components/Find/index.vue'
import { formateData } from '@/plugins/mixinJ'
import LoginWork from '@/utils/LoginWork'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'RdDepartmentDay'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref } from 'vue'
import { ElMessage, type UploadProps } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令号',
    inputValue: ''
  },
  {
    type: 'select',
    selectP: '节点',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '品牌',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入货号',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '计划日期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '导入计划'
  },
  {
    type: 'button',
    checkboxLabel: '导出计划'
  }
])

const imgList = ref([])
const tableHeader = ref([
  {
    label: '节点',
    prop: 'line'
  },
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '品牌',
    prop: 'custStyle'
  },
  {
    label: '货号',
    prop: 'style'
  },
  {
    label: '颜色',
    prop: 'color'
  },
  {
    label: '数量',
    prop: 'qty'
  },
  {
    change: true,
    type: 'dateSingle',
    label: '客户交期',
    prop: 'deliveryDate'
  },
  {
    type: 'dateSingle',
    label: '节点计划完成日期',
    prop: 'completeDate'
  },
  {
    type: 'img',
    label: '图片',
    fixed: true,
    prop: 'photoPath',
    srcList: imgList
  }
])

// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '导入计划') {
    upload()
  }
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '导出计划') {
    if (!formList.value[4].dateValue) {
      JMessage.warning('请选择计划日期')
      return
    }
    const res = (await fileRequest.post(`/prod/develop/downloadDayPlanList`, {
      endTime: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '计划日期'
      )?.dateValue?.[1],
      line: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '节点')
        ?.selectValue
        ? formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '节点')
            ?.selectValue
        : '物料',
      startTime: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '计划日期'
      )?.dateValue?.[0],
      style: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入货号'
      )?.inputValue,
      brand: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
        ?.selectValue,
      lotNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令号'
      )?.inputValue,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    // const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
    link.download = '研发部门日计划导出.xls' //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}
const upload = async () => {
  const fileType = ['xls', 'xlsx']
  const inputFile = document.createElement('input')
  const maxFileSizeMb = 2
  const maxFilesSizeBytes = maxFileSizeMb * 1024 * 1024
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.addEventListener('change', async function () {
    const files = inputFile.files as any // 获取文件数组
    const file = files[0] // 获取第一个文件对象
    const fileExtension = file.name.split('.').pop()
    if (!fileType.includes(fileExtension as any)) {
      JMessage.warning('上传的文件格式只能是 xls, xlsx')
      document.body.removeChild(inputFile)
      return false
    }
    if (file.size > maxFilesSizeBytes) {
      JMessage.warning('文件大小不能超过2MB!!!')
      document.body.removeChild(inputFile)
      return
    }
    const formData = new FormData() as any
    formData.append('file', file) // 添加文件对象及文件名
    let result = {} as any
    result = (await LoginWork.post('/prod/uploadPcOrderShoePlan', formData)) as any
    if (result.code === 200) {
      JMessage.success(result.message)
      getTableList()
    } else {
      JMessage.error(result.message)
    }
  })
  inputFile.click()
}
const tableData = ref([])
const isLoading = ref(true)

// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}

// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/prod/develop/devPartDayPlanList', {
    endTime: formList.value.find((item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '计划日期')
      ?.dateValue?.[1],
    line: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '节点')
      ?.selectValue,
    startTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '计划日期'
    )?.dateValue?.[0],
    style: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入货号'
    )?.inputValue,
    brand: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      ?.selectValue,
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令号'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading.value = false
  imgList.value = tableDataList.list.map((item: any) => {
    return item.photoPath
  })
  tableData.value = tableDataList.list.map((item: any) => {
    item.completeDate = item.completeDate.split(' ')[0]
    item.deliveryDate = item.deliveryDate.split(' ')[0]
    return item
  })
  total.value = tableDataList.total
  // currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)

// 下拉框数据初始化
const getSelectList = async (mid: any = '', small: any = '') => {
  let node = formList.value.find(
    (item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '节点'
  ) as formListType
  await selectList(formList, () => service.get('/back/order/allOrderCondition'))
  const nodes = await service.get<any, any>('/prod/develop/getLine')
  if (node && nodes) {
    nodes.list.forEach((item: any, index: any) => {
      if (item === null) return
      node.selectOptions?.push({
        optionKey: index,
        optionValue: item.planType,
        optionLabel: item.planType,
        LeftLabel: item.planType,
        RightLabel: item.seqNo
      })
    })
  }
}
onMounted(() => {
  getSelectList()
})

// 修改后点击确定按钮
const confirmChange = async (row: any) => {
  const copyData = formateData([row])
  const res = await LoginWork.post<any, any>(`/prod/develop/radPartDayPlan?choose=${1}`, copyData[0])
  if (res.code === 200) {
    JMessage.success('修改成功')
    getTableList()
  } else {
    JMessage.error(res.message)
  }
}
const currentTableRow = ref()
const removeCurrentRow = async () => {
  const copyData = formateData([currentTableRow.value])
  const res = await LoginWork.post<any, any>(`/prod/develop/radPartDayPlan?choose=${2}`, copyData[0])
  if (res.code === 200) {
    JMessage.success('删除成功')
    getTableList()
  } else {
    JMessage.error(res.message)
  }
}
// 点击表给另一张表传数据
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
}
</script>

<style lang="less" scoped></style>
